import 'package:boss/models/commodity.dart';
import 'package:boss/ui/page/commodity/categories/page/searchCommodity/search_commodity_page.dart';
import 'package:boss/ui/page/commodity/categories/widget/categories_search_bar.dart';
import 'package:boss/ui/page/commodity/pickerCategories/picker_commodity_provider.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import 'categoriesCommodityBrowser/categories_commodity_browser.dart';
import 'categories_footer.dart';

class CategoriesBrowser extends StatefulWidget {
  @override
  _CategoriesBrowserState createState() => _CategoriesBrowserState();
}

class _CategoriesBrowserState extends State<CategoriesBrowser> {
  ItemScrollController commodityScrollController;

  @override
  void initState() {
    super.initState();

    commodityScrollController = ItemScrollController();
  }

  _search(Commodity searchCommodity) {
    var commodityProvider = Provider.of<PickerCommodityProvider>(context, listen: false);

    var searchMenu = commodityProvider.storeMenus.firstWhere((menu) {
      return menu.commodityList.any((commodity) => commodity == searchCommodity);
    }, orElse: () => null);

    if (searchMenu != null) {
      //切换到对应的分类
      var menuIndex = commodityProvider.storeMenus.indexOf(searchMenu);
      commodityProvider.setStoreMenuSelectIndex(menuIndex);

      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        //滚动到菜品所在的位置
        var commodityIndex = commodityProvider.currentCommoditys.indexWhere((commodity) => commodity == searchCommodity);

        commodityScrollController.jumpTo(index: commodityIndex);
      });
    } else {
      toast('未找到对应的菜品');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        GestureDetector(
          onTap: () async {
            var commodityProvider = Provider.of<PickerCommodityProvider>(context, listen: false);
            var result = await searchCommodity(context, commodityProvider.storeMenus);
            if (result != null) {
              _search(result);
            }
          },
          behavior: HitTestBehavior.translucent,
          child: CategoriesSearchBar(enabled: false),
        ),
        CategoriesCommodityBrowser(commodityScrollController: commodityScrollController),
        CategoriesFooter(),
      ],
    );
  }
}
